import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: () => import('@/views/login') },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/layout'),
      children: [
        { path: '/home', component: () => import('@/views/layout/home') },
        { path: '/category', component: () => import('@/views/layout/category') },
        { path: '/cart', component: () => import('@/views/layout/cart') },
        { path: '/user', component: () => import('@/views/layout/user') }
      ]
    },
    { path: '/search', component: () => import('@/views/search') },
    { path: '/searchlist', component: () => import('@/views/search/list') },
    { path: '/prodetail/:id?', component: () => import('@/views/prodetail') },
    { path: '/pay', component: () => import('@/views/pay') },
    { path: '/myorder', component: () => import('@/views/myorder') },
    { path: '/addresslist', component: () => import('@/views/address/addressList.vue') },
    { path: '/addressedit', component: () => import('@/views/address/addressEdit.vue') }
  ]
})

// 所有的路由在真正被访问到之前都会经过这个全局前置守卫
// 只有全局前置守卫放行了，路由才能被访问
// to: 要去的地方 from: 从哪来  next: 是否放行 next() 放行 next('/login') 强制跳转
// 定义一个数组，存放权限页面地址
const authUrls = ['/pay', '/myorder']
// 1. 先判断是否为权限页面 2. 判断是否有token
router.beforeEach((to, from, next) => {
  // 如果要去的地方是登录页，直接放行
  // console.log(to, from, next)
  if (!authUrls.includes(to.path)) {
    // 非权限页面，直接放行
    return next()
  }
  // 如果要去的地方不是登录页，判断token是否存在
  store.getters.token ? next() : next('/login')
})

export default router
